<template>
  <div class="import">
    <el-card>
      <h3>批量导入员工信息</h3>
      <el-alert
        title="每次导入仅可添加1000名员工，姓名、手机、入职时间、聘用形式为必填项"
        type="warning"
        show-icon
      >
      </el-alert>
      <uploadExcel
        :beforeUpload="beforeUpload"
        :onSuccess="onSuccess"
      ></uploadExcel>
    </el-card>
  </div>
</template>

<script>
import { addEmpListApi } from '../../api/employees'
export default {
  methods: {
    // 批量新增请求
    async addEmpList(data) {
      await addEmpListApi(data)
      this.$message.success('批量新增成功')
      this.$router.push('/employees')
    },
    // excel时间转Js时间
    formatTime(days) {
      const time = new Date((days - 1) * 24 * 60 * 60 * 1000 + 1)
      time.setYear(time.getFullYear() - 70)
      return time.toString()
    },
    // 上传文件读取excel后
    onSuccess({ results }) {
      const obj = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }

      const arr = results.map(item => {
        const newValue = {}
        Object.keys(obj).forEach(subitem => {
          if (
            obj[subitem] === 'timeOfEntry' ||
            obj[subitem] === 'correctionTime'
          ) {
            newValue[obj[subitem]] = this.formatTime(item[subitem])
          } else {
            newValue[obj[subitem]] = item[subitem]
          }
        })
        return newValue
      })
      console.log(arr)
      this.addEmpList(arr)
    },

    // 选择上传文件确认之后
    beforeUpload(file) {
      const less2M = file.size < 2 * 1024 * 1024
      if (!less2M) {
        this.$message.error('上传的文件不能大于2M')
      }
      return less2M
    }
  }
}
</script>

<style lang="scss" scoped>
.import {
  padding: 20px;
  h3 {
    text-align: center;
  }
  .el-alert {
    margin-bottom: 20px;
  }
}
</style>